<?php

namespace App\Http\Resources;

use App\Models\BookCommentsStart;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Auth;

class BookCommentsResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => (int)$this->id,
            'content' => $this->content,
            'module_id' => $this->module_id,
            'status' => $this->status,
            'pid' => $this->pid,
            'like_num' => (int)$this->like_num,
            'cai_num' => (int)$this->cai_num,
            $this->mergeWhen($this->getUserId(), function () {
                return [
                    'this_like' => BookCommentsStart::where('comments_id', $this->id)
                        ->where('user_id', $this->getUserId())
                        ->where('type', 1)
                        ->where('status', 1)->exists(),
                    'this_cai' => BookCommentsStart::where('comments_id', $this->id)
                        ->where('user_id', $this->getUserId())
                        ->where('type', 2)
                        ->where('status', 1)->exists(),
                ];
            }),
            'created_at' => (string)$this->created_at,
            'book' => new BooksResource($this->whenLoaded('book')),
            'user' => new UserResource($this->whenLoaded('user')),
        ];
    }

    public function getUserId()
    {
        if ($user = Auth::guard('api')->user()) {
            return $user->id;
        } else {
            return 0;
        }
    }
}
